import {FileDownloader} from "./FileDownloader";
import {GeneratorFactory} from "../executor/GeneratorFactory";
import {GeneratorExecutor} from "../executor/GeneratorExecutor";
const path = require('path');
const fs = require("fs");

export class ThumbDownloader {

    constructor(){}

    static asyncDownloadThumbs(request, downloadParams){
        let thumbMap = ThumbDownloader.fromDownloadParamToThumbs(downloadParams);
        let thumbs = Array.from(thumbMap,item => {return item.thumbUrl});
        request.getUrlByThumbs({
            thumbs
        }).then(response => {
            let thumbUrls = response.returnValue.thumbUrls;
            let promiseArr = [];
            thumbUrls.forEach((thumbUrl ,index)=> {
                let thumb = thumbUrl.match(/static.kquestions.com\/(\S*)\?/)[1];
                var metaType = ''
                var resourceId = ''
                thumbMap.forEach((item ,i) =>{
                    if (i == index) {
                        metaType = item.metaType
                        resourceId = item.resourceId
                    }
                })
                let resourceDir = path.resolve(window.$DATADIR, "resc", metaType  , resourceId);
                console.log('resourceDir-------------',resourceDir);
                // return
                if(!fs.existsSync(resourceDir)){
                    fs.mkdirSync(resourceDir);
                }
                let downloadPromise = function(){
                    return new Promise((resolve, reject) => {
                        //优化下载缩略图
                        try{
                            let thumbPath = path.resolve(resourceDir, "thumb");
                            let downloader = new FileDownloader(thumbUrl, thumbPath);
                            if(fs.existsSync(thumbPath)){
                                fs.unlinkSync(thumbPath);
                            }
                            downloader.downloadFile(null, null, function () {
                                resolve("success");
                            }, function () {
                                reject("error");
                            });
                        }catch (e) {
                            console.log("ThumbDownloader::downloadPublisherThumbs  ->>> thumb:" + thumb, e)
                        }
                    });
                }
                promiseArr.push(downloadPromise);
            });
            //单课时缩略图串行下载
            let gen = GeneratorFactory.createGenerator(promiseArr);
            let executor = new GeneratorExecutor();
            executor.run(gen, function () {
                console.log("单个课时缩略图下载完成！")
            })
        });
    }
    static asyncDownloadSubtitles(request, downloadParams){
        console.log('下载字幕downloadParams',downloadParams);
        let subtitlesMap = ThumbDownloader.fromDownloadParamToSubtitles(downloadParams);
        console.log(subtitlesMap);
        downloadParams.forEach(param=>{
            if(param.FileType == "BosVideo"){
                let bsr = param.Bsr;
                if(bsr){
                    bsr = JSON.parse(bsr);
                    if(!bsr.meta_info.subtitles){
                        let resourceDir = path.resolve(window.$DATADIR, "resc", 'BosVideo', param.TaskId);
                        let downloadedPath = path.resolve(resourceDir, "subtitle.vtt");
                        if(fs.existsSync(downloadedPath)){
                            console.log('该视频字幕文件被后台删除');
                            fs.unlinkSync(downloadedPath);
                        }
                    }
                }
            }
        })
        let subtitles = Array.from(subtitlesMap.keys());
        if (subtitles == []) {
            return
        }
        console.log(subtitles);
        let promiseArr = [];
        subtitles.forEach(item=>{
            
            let resourceDir = path.resolve(window.$DATADIR, "resc", 'BosVideo', subtitlesMap.get(item).resourceId);
            if(!fs.existsSync(resourceDir)){
                fs.mkdirSync(resourceDir);
            }
            let downloadPromise = function(){
                return new Promise((resolve, reject) => {
                    //优化下载缩略图
                    try{
                        let subtitlesPath = path.resolve(resourceDir, "subtitle.vtt");
                        let downloader = new FileDownloader(item, subtitlesPath);
                        if(fs.existsSync(subtitlesPath)){
                            fs.unlinkSync(subtitlesPath);
                        }
                        downloader.downloadFile(null, null, function () {
                            resolve("success");
                        }, function () {
                            reject("error");
                        });
                    }catch (e) {
                        console.log("ThumbDownloader::downloadPublisherSubtitles  ->>> subtitles:" + item, e)
                    }
                });
            }
            promiseArr.push(downloadPromise);
        })
        let gen = GeneratorFactory.createGenerator(promiseArr);
        let executor = new GeneratorExecutor();
        executor.run(gen, function () {
            console.log("单个课时字幕文件下载完成！")
        })

    }
    static fromDownloadParamToThumbs(downloadParams){
        // Map对象改为Array对象,Map的set方法（此前以thumb为key）当添加数据时，添加的数据中两个键名重复时，新的数据会覆盖旧的数据，导致一课中若有多个相同封面图的资源时，只下载一个封面
        // let thumbUrls = new Map();
        let thumbUrls = [];
        if(downloadParams instanceof Array){
            downloadParams.forEach(param => {
                console.log('param' , param);
                if (param.FileType == "selfPpt" ||
                    param.FileType == "selfPdf" || 
                    param.FileType == "selfWord" ||
                    param.FileType == "selfImg" ||
                    param.FileType == "selfVideo" ||
                    param.FileType == "selfAudio" ) {
                    console.log('自上传资源不需要下载封面');
                    return
                }
                
                if(param.FileType !== "selfPpt"){
                    let bsr = param.Bsr;
                    if(bsr){
                        bsr = JSON.parse(bsr);
                        let thumb = ''
                        if(bsr.thumb){
                            thumb = bsr.thumb;
                        }else {
                            if(bsr.meta_info.filekey){
                                thumb = bsr.meta_info.filekey
                            }else {
                                if(bsr.meta_info.thumb){
                                    thumb = bsr.meta_info.thumb
                                }
                            }
                        }
                        if(thumb.startsWith("https://")){
                            thumb = thumb.match(/static.kquestions.com\/(\S*)\?/)[1]
                        }
                        thumbUrls.push({
                            thumbUrl: thumb,
                            resourceId: param.TaskId,
                            metaType: param.FileType
                        });
                    }
                }
            });
            return thumbUrls;
        }
    }
    static fromDownloadParamToSubtitles(downloadParams){
        let subtitleUrls = new Map();
        if(downloadParams instanceof Array){
            downloadParams.forEach(param => {
                if(param.FileType == "BosVideo"){
                    let bsr = param.Bsr;
                    if(bsr){
                        bsr = JSON.parse(bsr);
                        let subtitles = ''
                        if(bsr.meta_info.subtitles){
                            subtitles = bsr.meta_info.subtitles;
                            subtitleUrls.set(subtitles, {
                                subtitles: subtitles,
                                resourceId: param.TaskId,
                                metaType: param.FileType
                            });
                        } else {
                            // console.log('没有字幕文件',bsr);
                        }
                    }
                }
            });
            return subtitleUrls;
        }
    }
    /**
     * 下载教材列表的缩略图
     * @param thumbUrls
     */
    static downloadPublisherThumbs(thumbUrls){
        let promiseArr = [];
        thumbUrls.forEach(thumbUrl => {
            let thumb = thumbUrl.match(/static.kquestions.com\/(\S*)\?/)[1];
            let resourceDir = path.resolve(window.$DATADIR, "resc", "publisher");
            if(!fs.existsSync(resourceDir)){
                fs.mkdirSync(resourceDir);
            }
            let downloadPromise = function(){
                return new Promise((resolve, reject) => {
                    //优化下载缩略图
                    try {
                        let thumbPath = path.resolve(resourceDir, thumb);
                        let downloader = new FileDownloader(thumbUrl, thumbPath);
                        if(fs.existsSync(thumbPath)){
                            fs.unlinkSync(thumbPath);
                        }
                        downloader.downloadFile(null, null, function () {
                            resolve("success");
                        }, function () {
                            reject("error");
                        });
                    }catch (e) {
                        console.log("ThumbDownloader::downloadPublisherThumbs  ->>> thumb:" + thumb, e)
                    }
                    // if(fs.existsSync(thumbPath)){
                    //     FileDownloader.getTotalSize(thumbUrl, function (totalSize) {
                    //         downloader.totalSize = totalSize;
                    //         downloader.checkDownload(function (status) {
                    //             if(status){
                    //                 downloader.downloadFile(null, null, function () {
                    //                     resolve("success");
                    //                 }, function () {
                    //                     reject("error");
                    //                 });
                    //             }else {
                    //                 resolve("success");
                    //             }
                    //         })
                    //     })
                    // }else {
                    //     downloader.downloadFile(null, null, function () {
                    //         resolve("success");
                    //     }, function () {
                    //         reject("error");
                    //     });
                    // }
                });
            }
            promiseArr.push(downloadPromise);
        });
        //单课时缩略图串行下载
        let gen = GeneratorFactory.createGenerator(promiseArr);
        let executor = new GeneratorExecutor();
        executor.run(gen, function () {
            console.log("下载教材列表的缩略图完成！")
        })
    }

    /**
     * 下载特殊资源的缩略图
     * @param pptThumbs
     * @param type  支持 courseware 、quiz
     */
    static downloadPptThumbs(pptThumbs){
        let promiseArr = [];
        pptThumbs.forEach(thumbInfo => {
            let thumbUrl = thumbInfo.thumb;
            let resourceDir = "";
            if(thumbInfo.type === "Quiz"){
                resourceDir = path.resolve(window.$DATADIR, "resc", "Quiz", thumbInfo.id);
            }else if(thumbInfo.type === "courseware"){
                resourceDir = path.resolve(window.$DATADIR, "resc", "courseware", thumbInfo.id);
            }
            if(!fs.existsSync(resourceDir)){
                fs.mkdirSync(resourceDir);
            }
            let downloadPromise = function(){
                return new Promise((resolve, reject) => {
                    //优化下载缩略图
                    if(thumbInfo.type === "Quiz"){
                        let exsistThumb = "";
                        if(process.env.NODE_ENV === 'production'){
                            exsistThumb = path.dirname(process.execPath) + '/resources/data/icons/quiz_thumb';
                        }else {
                            exsistThumb = './data/icons/quiz_thumb'
                        }
                        fs.copyFile(exsistThumb, path.resolve(resourceDir, "thumb"), function () {
                            resolve("Quiz copy thumb success");
                        });
                    }else if(thumbInfo.type === "courseware"){
                        let downloader = new FileDownloader(thumbUrl, path.resolve(resourceDir, "thumb"));
                        downloader.downloadFile(null, null, function () {
                            resolve("thumb success");
                        }, function () {
                            reject("error");
                        });
                    }
                });
            }
            promiseArr.push(downloadPromise);
        });
        //单课时缩略图串行下载
        let gen = GeneratorFactory.createGenerator(promiseArr);
        let executor = new GeneratorExecutor();
        executor.runSingleWithTimeOut(gen, 30, function () {
            console.log("下载特殊资源的缩略图完成！")
        })
    }
}
